<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/t/hplus/include/taglib.jsp"%>

<!DOCTYPE html>
<html>

<head>
    <title>用户管理</title>
	<%@ include file="/WEB-INF/t/hplus/include/head.jsp"%>
	<link href="${ctxStatic}/css/plugins/ztree/zTreeStyle.css" rel="stylesheet">
	<link href="${ctxStatic}/css/plugins/select2/select2.min.css" rel="stylesheet">
	<style type="text/css">
	 /*ztree增加按钮的样式 */
	 .ztree li span.button.add {margin-left:2px; margin-right: -1px; background-position:-144px 0; vertical-align:top; *vertical-align:middle}
	 /*（1）select2在modal里不显示搜索框问题, 第1方案去掉modal上的tabindex="-1", 第2方案修改下面样式的z-index, 
	        （2）出现搜索框但不能聚焦问题，在ready里加$.fn.modal.Constructor.prototype.enforceFocus = function() {};
	        （3）不能聚焦有选中，给select2加个id试试*/ 
	 .select2-dropdown{z-index: 3051 !important;/*99*/}
	</style>
</head>

<body>
    <div class="wrapper wrapper-content">
   	   <div class="row"> 
	    <div class="col-sm-2" style="overflow: hidden"> 
	     <div class="float-e-margins"> 
	      <div class="no-padding"> 
			<ul id="organizationTree" data-toggle="organizationTree" class="ztree"></ul>
	      </div> 
	     </div> 
	    </div> 
	    <div class="col-sm-10"> 
	     <div class="float-e-margins"> 
	      <div class="no-padding"> 
			<div id="userToolbar" class="btn-group hidden-xs" role="group"> 
			 <button type="button" class="addUser btn btn-outline btn-default" title="添加用户"> <i class="glyphicon glyphicon-plus" aria-hidden="true"></i> 添加</button> 
			</div>
			<table id="userList"></table>
	      </div> 
	     </div> 
	    </div> 
	   </div> 
    </div>
    
<div id="userModal" class="modal fade" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content animated bounceInUp">
	       <form class="form-horizontal" id="userForm">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span></button>
				<h4 class="modal-title"></h4>
			</div>
			<div class="modal-body" style="overflow:hidden;">
		        <input type="hidden" id="id" name="id">
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">登录名称：</label> 
		         <div class="col-sm-8"> 
		          <input id="loginName" name="loginName" class="form-control" type="text"> 
		         </div> 
		        </div> 
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">真实姓名：</label> 
		         <div class="col-sm-8"> 
		          <input id="realName" name="realName" class="form-control" type="text"> 
		         </div> 
		        </div> 
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">所属机构：</label> 
		         <div class="col-sm-8"> 
                      <select id="organizationId" name="organizationId" class="js-states form-control" style="width: 100%"></select>
		         </div> 
		        </div> 
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">是否禁用：</label> 
		         <div class="col-sm-8"> 
                     <div class="radio i-checks">
                         <input type="radio" value="1" name="isDisabled"> <i></i> 是
                         <input type="radio" value="0" name="isDisabled" checked="checked" > <i></i> 否
                     </div>
		         </div> 
		        </div> 		        
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">用户角色：</label> 
		         <div class="col-sm-8"> 
                     <div id="roleList"></div>
		         </div> 
		        </div> 		        
			</div>
			<div class="modal-footer">
		          <button class="btn btn-primary" type="submit">提交</button> 
		          <button class="btn btn-white" type="submit" data-dismiss="modal">关闭</button>
			</div>
			</form> 
		</div>
	</div>
</div>  

<div class="modal fade" id="delModal" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content animated bounceInUp">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">删除用户</h4>
            </div>
            <div class="modal-body">
                <p>确定删除该用户吗？</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-white" data-dismiss="modal">放弃</button>
                <button type="button" class="btn btn-primary" id="delOk">确定</button>
            </div>
        </div>
    </div>
</div>

<script src="${ctxStatic}/js/plugins/ztree/jquery.ztree.all-3.5.min.js"></script> 
<script src="${ctxStatic}/js/plugins/select2/select2.full.min.js"></script>
<script src="${ctxStatic}/js/plugins/select2/i18n/zh-CN.js"></script>

<script type="text/javascript">
$.fn.modal.Constructor.prototype.enforceFocus = function() {};
	var $table = $("#userList"),
		$delModal = $('#delModal'),
		$s2Org,
		ztreeSetting = {
			view: {
				addHoverDom: addHoverDom,
				removeHoverDom: removeHoverDom,
				selectedMulti: false
			},
			data: {
				simpleData: {
					enable: true
				}
			},
			callback: {
				onClick: onClick
			}
		}
	$(document).ready(function(){
		
		loadOrganizationTree();
		
		loadUserList();
		
		$('.addUser').click(function () {
			showModal("添加用户");
	    });
		
		//提示信息样式
		toastr.options = {
			closeButton: true,
			progressBar: true,
			positionClass: "toast-top-right", //toast-top-center, toast-top-right
			onclick: null,
			timeOut: 2000
		};
		
	});
	
	function onClick(event, treeId, treeNode){
		$table.bootstrapTable('refresh',{url:'${ctx}/user/list', query:{limit:10,offset:0}});
	}
	
	function showRemoveBtn(treeId, treeNode) {
		return false;
	}
	
	function showRenameBtn(treeId, treeNode) {
		return false;
	}
	
	function addHoverDom(treeId, treeNode) {
		var sObj = $("#" + treeNode.tId + "_span");
		if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
		var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
			+ "' title='添加用户' onfocus='this.blur();'></span>";
		sObj.after(addStr);
		var btn = $("#addBtn_"+treeNode.tId);
		if (btn) btn.bind("click", function(){
			//addUser(treeNode.id);
			var treeObj = $.fn.zTree.getZTreeObj("organizationTree");
			var node = treeObj.getNodeByTId(treeNode.tId);
			treeObj.selectNode(node);
			showModal("添加用户");
			return false;//阻止冒泡事件
		});
	};
	
	function removeHoverDom(treeId, treeNode) {
		$("#addBtn_"+treeNode.tId).unbind().remove();
	};
	
	function loadOrganizationTree() {
		$.ajax({
			type : "GET",
			url : '${ctx}/organization/ztlist',
			async : false,
			success : function(data) {
				$.fn.zTree.init($("#organizationTree"), ztreeSetting, data);
			}
		});
	}
	
	function loadUserList(){
		$table.bootstrapTable({
			url: "${ctx}/user/list", //get请求, 如果cache为false默认会加随机数, 如果列排序sortable=true则还会加sort和order
			cache: false,
			pagination: true,
	        sidePagination: 'server', // client or server
	        dataField: 'list',
	        pageNumber: 1,
	        pageSize: 10,
	        pageList: [10, 25, 50, 100],
	        selectItemName: 'userIds',
			showRefresh: true,
			showToggle: true,
			showColumns: true,
	        toolbar: '#userToolbar',
	        iconSize : "outline",
	        queryParams: 'queryParams',
	        rowStyle: function(row, index){
	        	if(row.isDisabled == 1){
					return {
		            	classes: 'danger'
		        	};
	        	}else{
	        		return {}
	        	}
	        },
	        columns:[{
	        	field:'loginName',
	        	title:'登录名称',
	        	width: 150,
	        	align:'center'
	        },{
	        	field:'realName',
	        	title:'真实姓名',
	        	align:'center'
	        },{
	        	field:'organizationId',
	        	title:'所属机构',
	        	align:'center'
	        	//sortable: true,
	        	//sortOrder: "asc"
	        },{
	        	field:'isDisabled',
	        	title:'是否禁用',
	        	align:'center',
	        	formatter: function(value, row, index){
					switch(value){
						case 1 :
							return '禁用';
							break;
						case 0 :
							return '正常';
							break;
					}
				}
	        },{
	        	field:'createTime',
	        	title:'创建时间',
	        	align:'center'
	        },{
	        	field:'action',
	        	title:'操作',
	        	align:'center',
	        	formatter: function(value, row, index){
					var str = '&nbsp;';
					str += '<a href="javascript:void(0)" onclick="editUser('+ row.id +');" >编辑</a>';
					str += '&nbsp;|&nbsp;';
					str += '<a href="javascript:void(0)" onclick="showDelModal('+ row.id +');" >删除</a>';
					str += '&nbsp;';
					return str;
				}
	        }]
		});
	}
	
	function queryParams(params){
		var node = getSelectNode() || {};
		params.organizationId = node.id;
		return params;
	}
	
	function editUser(id){
		$.ajax({
			type: "GET",
			async: false,
			data: {"id": id, "r": Math.random()},
			dataType: "json",
			url: "${ctx}/user/get",
			success: function(data){
				showModal("编辑用户", data);
			},
			error: function(){
				toastr.error("查询用户失败！");
			}
		});
	}
	
	
	function showDelModal(id){
		$delModal = $('#delModal').modal({
			"backdrop": 'static',
			"show": true
		});
		
		$('#delOk').off();
		$('#delOk').on('click', function(){
			deleteUser(id);
		});
		
		$delModal.modal('show');
	}
	
	function deleteUser(id){
		$.ajax({
			type: "POST",
			async: false,
			data: {"id": id},
			dataType: "json",
			url: "${ctx}/user/delete",
			success: function(data){
				if(data.success){
					$delModal.modal("hide");
					afterCRUD();
					toastr.success(data.msg);
				}else{
					$delModal.modal("hide");
					toastr.error(data.msg);
				}
			},
			error: function(){
				$delModal.modal("hide");
				toastr.error("删除用户失败！");
			}
		});
	}
	
	function showModal(title, row) {
		$('#userModal').off();
		
		var $modal = $('#userModal').modal({
			"backdrop": 'static', //禁止模态失去焦点关闭
			"show": true
		});
		$modal.find('.modal-title').text(title);
		
		getRoles();
		
		//iCheck
		$(".i-checks").iCheck({
			checkboxClass:"icheckbox_square-green",
			radioClass:"iradio_square-green"
		});
		
		
		$('#userModal').on("shown.bs.modal", function(){
			$("#loginName").focus();
			initSelect2Org(row);
		});
		$('#userModal').on("hidden.bs.modal", function(){
			//重置表单
			$("#userForm")[0].reset();
			$("#id").val("");
			$modal.find('input:radio[name=isDisabled][value=0]').iCheck('check');
			
			$s2Org.select2("destroy");
		});
		
		//表单赋值
		if(row){
			for (var name in row) {
				switch(name){
					case "roles" :
						$.each(row[name], function(i,n){
							$modal.find('input:checkbox[name=roles][value='+n.id+']').iCheck('check');
						});
						break;
					case "isDisabled" :
						$modal.find('input:radio[name='+name+'][value='+row[name]+']').iCheck('check');
						break;						
					default:
						$modal.find('input[name='+name+']').val(row[name]);
				}
			}
		}
		
		//表单校验及提交
		var e = "<i class='fa fa-times-circle'></i> ";
		$("#userForm").validate({
			rules : {
				loginName : {
					required : !0,
					minlength : 1,
					maxlength : 20
				},
				realName : {
					required : !0,
					minlength : 1,
					maxlength : 20
				}
			},
			messages : {
				loginName : {
					required : e + "请输入登录名称",
					minlength : e + "登录名称必须1字符以上",
					maxlength : e + "登录名称最多20个字符"
				},
				realName : {
					required : e + "请输入真实",
					minlength : e + "真实姓名必须1字符以上",
					maxlength : e + "真实姓名最多20个字符"
				}
			},
			submitHandler: function(form){
				$(form).ajaxSubmit({
					type: "POST",
					dataType: "json",
					url: "${ctx}/user/save",
					success: function(data){
						if(data.success){
							$modal.modal("hide");
							afterCRUD();
							toastr.success(data.msg);
						}else{
							toastr.error(data.msg);
						}
					},
					error: function(data){
						toastr.error("保存机构失败！");
					}
				});
			}
		});
	}
	
	function getRoles(){
		$.ajax({
			type: "GET",
			async: false,
			data: {},
			dataType: "json",
			url: "${ctx}/role/list",
			success: function(data){
				var mhtml = "";
				$.each(data, function(i,n){
					mhtml += '<label class="checkbox-inline i-checks">';
					mhtml += '<input type="checkbox" value="'+n.id+'" name="roles">'+n.name+'</label>';
				});
				$("#roleList").html(mhtml);
			},
			error: function(){
				toastr.error("查询角色失败！");
			}
		}); 
	}
	
	function initSelect2Org(row){
		var node = {"id" : 0, "name" : "请选择所属机构"};
		if(row && row["organizationId"] && row["organizationId"] != 0){
			node.id = row["organizationId"];
			node.name = row["organizationName"];
		}else{
			node = getSelectNode() || node;
		}
		$("#organizationId").html('<option value="'+node.id+'" selected="selected">'+node.name+'</option>');
		//$s2Parent.val(node.id).trigger("change");
		$s2Org = $("#organizationId").select2({
			id: "sssss2Org",
			language: "zh-CN",
			/*placeholder: {
				id: node.id,
				name: node.name
			} ,*/
			//allowClear:true,
			//theme: "bootstrap",
			ajax: {
				type: "GET",
				async: false,
				dataType: "json",
				url: "${ctx}/organization/list",
				delay: 500,
				data: function(params){
					params.page = params.page || 1;
					var query = {
						name: params.term, // ? encodeURI(encodeURI(params.term)) : ""
						limit: 10,
						offset: (params.page-1)*10
					}
					return query;
				},
				processResults: function (data, params) {
					params.page = params.page || 1;
			        return {
			        	results: data.list,
			        	pagination: {
			                more: params.page < data.totalPages
			            }
			        };
				},
				cache: false,
				error: function(data){
					toastr.error("查询机构失败！");
					$modal.modal("hide");
				}
			},
			escapeMarkup: function (markup) {
				return markup;   
			},
			minimumInputLength: 1,
			templateResult: function(repo){
				if (repo.loading) return repo.text;
				return repo.name;
				/*if(repo.name){
					var markup = '<div class="clearfix">' +  
					'<div class="col-sm-2">' + repo.id + '</div>' +  
					'<div class="col-sm-8">' + repo.name + '</div>' +  
					'</div>';  
					 return markup;
				}*/
			},  
			templateSelection: function(repo){
				return repo.name || repo.text;
			}
		});
	}
	
	function getSelectNode(){
		var node;
		var zTree = $.fn.zTree.getZTreeObj("organizationTree");
		var nodes = zTree.getSelectedNodes();
		if(nodes.length > 0){
			node = nodes[0];
		}
		return node;
	}
	
	function afterCRUD(){
		$table.bootstrapTable("refresh");
	}
	
</script>

</body>
</html>